package com.hzyl.famousreader.view.fragment;


import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hzyl.famousreader.Constant;
import com.hzyl.famousreader.R;
import com.hzyl.famousreader.ThemeColor;
import com.hzyl.famousreader.databinding.FragmentCategoryBinding;
import com.hzyl.famousreader.repository.persistence.entity.Book;
import com.hzyl.famousreader.repository.webservice.RetrofitClient;
import com.hzyl.famousreader.repository.webservice.api.BookService;
import com.hzyl.famousreader.repository.webservice.cache.Resource;
import com.hzyl.famousreader.repository.webservice.model.Classification;
import com.hzyl.famousreader.repository.webservice.model.PageWrapper;
import com.hzyl.famousreader.repository.webservice.model.Result;
import com.hzyl.famousreader.view.adapter.BookshelfAdapter;
import com.hzyl.famousreader.view.adapter.ClassificationAdapter;
import com.hzyl.famousreader.viewmodel.BookViewModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.List;

/**
 * 分类
 */
@Route(path = "/main/category")
public class CategoryFragment extends BaseFragment {

  private static final int DEFAULT_PI = 1;
  private static final int DEFAULT_PS = 20;
  private static final long DEFAULT_TOTAL = 0;

  private FragmentCategoryBinding binding;

  private BookViewModel bookViewModel;

  private ClassificationAdapter classificationAdapter;

  private BookshelfAdapter bookshelfAdapter;

  /**
   * 分页参数：第几页
   */
  private int curPageIndex = DEFAULT_PI;

  /**
   * 分页参数：展示的数量
   */
  private int curPageSize = DEFAULT_PS;

  private long total = DEFAULT_TOTAL;

  private Long currentClassificationId = -1L;

  private int curSelectedClassification = 0;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {

    super.onCreateView(inflater, container, savedInstanceState);


    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_category, container, false);

    int colorId = SPUtils.getInstance().getInt(Constant.SP_THEME_COLOR,  ThemeColor.DEFAULT.getColor());
    BarUtils.setStatusBarColor(getActivity(), colorId, 0);
    binding.toolbar.setBackgroundColor(colorId);


    //分类
    classificationAdapter = new ClassificationAdapter(null);
    classificationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
      @Override
      public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if(curSelectedClassification == position) {
          return;
        }
        curSelectedClassification = position;

        //设置被选中的标签
        List<Classification> list = adapter.getData();
        Classification classification = list.get(position);
        classificationAdapter.setCurSelectedId(classification.getId());
        classificationAdapter.notifyDataSetChanged();

        binding.categorySvWrapper.scrollTo(0, 0);

        loadClassificationBooks(classification.getId());
      }
    });

    LinearLayoutManager layoutManager = new GridLayoutManager(getActivity(),6);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    binding.categoryRvClassification.setLayoutManager(layoutManager);
    binding.categoryRvClassification.setAdapter(classificationAdapter);

    //分类书籍
    bookshelfAdapter = new BookshelfAdapter(null);
    bookshelfAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
      @Override
      public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        List<Book> books = adapter.getData();
        Book book = books.get(position);
        ARouter.getInstance().build("/book/info").withObject("book", book).navigation();
      }
    });
    bookshelfAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
      @Override
      public void onLoadMoreRequested() {

      }
    }, binding.categoryRvBook);





    binding.categoryRvBook.setLayoutManager(new GridLayoutManager(getActivity(), 3));
    binding.categoryRvBook.setAdapter(bookshelfAdapter);

    binding.categorySvWrapper.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
      @Override
      public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
          //加载更多
          loadMore();
        }
      }
    });

    bookViewModel = ViewModelProviders.of(this).get(BookViewModel.class);
    bookViewModel.getBookClassification().observe(this, new Observer<Resource<List<Classification>>>() {
      @Override
      public void onChanged(@Nullable Resource<List<Classification>> listResource) {
        List<Classification> list = listResource.data;
        if(list != null && list.size() > 0) {
          Classification classification = list.get(0);

          classificationAdapter.setNewData(list);
          classificationAdapter.setCurSelectedId(classification.getId());
          classificationAdapter.notifyDataSetChanged();

          if(classification.getId() != currentClassificationId) {
            loadClassificationBooks(classification.getId());
          }
        }
      }
    });

    return binding.getRoot();
  }

  /**
   * 初始化加载分类书籍
   * @param classificationId
   */
  private void loadClassificationBooks(long classificationId) {
    curPageIndex = DEFAULT_PI;
    curPageSize = DEFAULT_PS;
    total = DEFAULT_TOTAL;

    currentClassificationId = classificationId;
    BookService bookService = RetrofitClient.getInstance().create(BookService.class);
    Call<Result<PageWrapper<Book>>> call = bookService.getClassificationBooks(curPageIndex, curPageSize, classificationId);
    call.enqueue(new Callback<Result<PageWrapper<Book>>>() {
      @Override
      public void onResponse(Call<Result<PageWrapper<Book>>> call, Response<Result<PageWrapper<Book>>> response) {
        Result<PageWrapper<Book>> result = response.body();
        LogUtils.d("获取数据");
        if(result != null && result.getData() != null) {
          PageWrapper<Book> pageWrapper = result.getData();
          total = pageWrapper.getTotal();
          LogUtils.d("总数是："+total);
          bookshelfAdapter.setNewData(pageWrapper.getList());
          if(total <= DEFAULT_PS) {
            bookshelfAdapter.disableLoadMoreIfNotFullPage();
          }
        }
      }

      @Override
      public void onFailure(Call<Result<PageWrapper<Book>>> call, Throwable t) {
        LogUtils.d("获取分类的书籍异常",t);
      }
    });
  }

  private void loadMore() {
    if(curPageIndex * curPageSize >= total) {
      bookshelfAdapter.loadMoreEnd();
      return;
    }

    curPageIndex++;
    BookService bookService = RetrofitClient.getInstance().create(BookService.class);
    Call<Result<PageWrapper<Book>>> call = bookService.getClassificationBooks(CategoryFragment.this.curPageIndex,
      CategoryFragment.this.curPageSize, currentClassificationId);
    call.enqueue(new Callback<Result<PageWrapper<Book>>>() {
      @Override
      public void onResponse(Call<Result<PageWrapper<Book>>> call, Response<Result<PageWrapper<Book>>> response) {
        Result<PageWrapper<Book>> result = response.body();
        if(result != null && result.getData() != null) {
          PageWrapper<Book> pageWrapper = result.getData();
          if(pageWrapper.getList().size() > 0) {
            CategoryFragment.this.total = pageWrapper.getTotal();
            bookshelfAdapter.addData(pageWrapper.getList());
            bookshelfAdapter.loadMoreComplete();
          } else {
            bookshelfAdapter.loadMoreFail();
          }
        } else {
          bookshelfAdapter.loadMoreFail();
        }
      }

      @Override
      public void onFailure(Call<Result<PageWrapper<Book>>> call, Throwable t) {
        bookshelfAdapter.loadMoreFail();
      }
    });
  }
}
